package com.newworld.dmsapp2.fragment;

import java.io.File;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.newworld.dmsapp2.LoginActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.SettingAccountActivity;
import com.newworld.dmsapp2.activity.SettingCacheActivity;
import com.newworld.dmsapp2.activity.SettingSoftwareVersionActivity;
import com.newworld.dmsapp2.activity.TwoDcode1;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.GetFileSize;
import com.newworld.dmsapp2.util.MyPreference;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;

@SuppressLint("ShowToast")
public class MainSettingFragment extends Fragment implements OnClickListener {
	private static TextView set_cache;
	private TextView set_version, set_account;
	private RelativeLayout ly_set_account, ly_set_cache,ly_set_twoDcode,
			ly_set_software_version, ly_set_exit_login;
	private User user;
	private static Context context;
	private Intent intent;
	private ProgressBar loginbar;
	// l1,l2分别是图片，录音的大小，k是两者和
	private static long l1, l2, k;
	/*private final static String PHOTO_PATH = Environment
			.getExternalStorageDirectory() + "/NewWorld_Photo";
	private final static String VOICE_PATH = Environment
			.getExternalStorageDirectory() + "/NewWorld_Voice";*/
	private final static String PHOTO_PATH = Config.IMAGE_PATH;
	private final static String VOICE_PATH = Config.VOICE_PATH;
	/*File parent1 = new File("/sdcard/NewWorld_APP2_Photo/");
	if (!parent1.exists()) {
		parent1.mkdirs();
	}
	File parent2 = new File("/sdcard/NewWorld_APP2_Voice/");*/	
	private Handler progressBarHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case Config.HANDLER_MSG_SUCCESS:// 成功
				MyPreference.getInstance(context).setUserId(0);
				Intent intent = new Intent();
				intent.setClass(getActivity(), LoginActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				loginbar.setVisibility(View.GONE);
				Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT)
						.show();
				break;
			case Config.HANDLER_MSG_FAIL:// 失败
				loginbar.setVisibility(View.GONE);
				Toast.makeText(context, "退出登录失败", Toast.LENGTH_SHORT).show();
				break;
			case Config.HANDLER_MSG_OVER:// 超时
				loginbar.setVisibility(View.GONE);
				Toast.makeText(context, "当前无网络", Toast.LENGTH_SHORT);

				break;
			case Config.HANDLER_MSG_NOTNET:// 未联网
				loginbar.setVisibility(View.GONE);
				Toast.makeText(context, "当前无网络", Toast.LENGTH_SHORT);
				Tool.setNetwork(context);

				break;
			default:
				break;
			}

		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_setting_main, container,
				false);
		context = this.getActivity();
		initData();
		findView(view);
		init();

		return view;
	}

	private void findView(View v) {
		set_cache = (TextView) v.findViewById(R.id.set_cashe);
		ly_set_account = (RelativeLayout) v.findViewById(R.id.ly_set_account);
		ly_set_cache = (RelativeLayout) v.findViewById(R.id.ly_set_cache);
		ly_set_software_version = (RelativeLayout) v
				.findViewById(R.id.ly_set_software_version);
		ly_set_exit_login = (RelativeLayout) v
				.findViewById(R.id.ly_set_exit_login);
		ly_set_twoDcode= (RelativeLayout) v
				.findViewById(R.id.ly_set_twoDcode);
		set_version = (TextView) v.findViewById(R.id.set_version);
		set_account = (TextView) v.findViewById(R.id.set_account);
		loginbar = (ProgressBar) v
				.findViewById(R.id.settingfragment_progressBar);
		ly_set_account.setOnClickListener(this);
		ly_set_cache.setOnClickListener(this);
		ly_set_software_version.setOnClickListener(this);
		ly_set_exit_login.setOnClickListener(this);
		ly_set_twoDcode.setOnClickListener(this);
		set_account.setText(user.getUsername());
		user.setUsername(set_account.getText().toString());
		user.update(user.getId());
		try {
			set_version.setText("当前版本：" + getVersionName());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void init() {
		init_records();
		init_pics();
		GetFileSize g7 = new GetFileSize();
		k = l1 + l2;
		set_cache.setText(g7.FormetFileSize(k) + "");
	}

	public static void init(String filesize) {
		
		  User user = SingleSample.getInstance(context).getUser();
		  String user_type = user.getUsertype();
		  init_records();
		  init_pics(); 
		  GetFileSize g3 = new GetFileSize();
		  k = l1 + l2;
		  set_cache.setText(g3.FormetFileSize(k)+"");
		  set_cache.setText(filesize);
	}

	private void initData() {
		user = SingleSample.getInstance(getActivity()).getUser();
	}

	@Override
	public void onClick(View avrg0) {
		// TODO Auto-generated method stub
		switch (avrg0.getId()) {
		case R.id.ly_set_account:
			intent = new Intent(context, SettingAccountActivity.class);
			startActivity(intent);
			break;
		case R.id.ly_set_cache:
			intent = new Intent(context, SettingCacheActivity.class);
			startActivity(intent);
			IntentFilter filter = new IntentFilter(SettingCacheActivity.action);
			registerReceiver(broadcastReceiver, filter);
			break;
		case R.id.ly_set_software_version:
			intent = new Intent(context, SettingSoftwareVersionActivity.class);
			startActivity(intent);
			break;
		case R.id.ly_set_twoDcode:
			intent = new Intent(context, TwoDcode1.class);
			startActivity(intent);
			break;
		case R.id.ly_set_exit_login:
			loginbar.setVisibility(View.VISIBLE);
			new Thread(logoutRun).start();
			break;
		default:
			break;
		}
	}

	Runnable logoutRun = new Runnable() {
		// 退出登录
		@Override
		public void run() {
			// TODO Auto-generated method stub
			// 判断有无网络
			if (Tool.isNetworkAvailable(context)) {
				String flag = "true";
				if (flag.equals(Config.CONNECT_SUCCESS)) {
					String message = "成功退出登录";
					progressBarHandler.obtainMessage(
							Config.HANDLER_MSG_SUCCESS, message).sendToTarget();// 成功
				} else {
					progressBarHandler
							.sendEmptyMessage(Config.HANDLER_MSG_FAIL);// 失败
				}
			} else {
				progressBarHandler.sendEmptyMessage(Config.HANDLER_MSG_NOTNET);// 未联网

			}

		}

	};

	private void registerReceiver(BroadcastReceiver broadcastReceiver2,
			IntentFilter filter) {
		// TODO Auto-generated method stub
	}

	// 监听SettingCacheActivity里面缓存变化
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			set_cache.setText(intent.getExtras().getString("data"));
		}
	};

	// 初始化图片
	private static void init_pics() {
		GetFileSize g4 = new GetFileSize();
		try {
			String path = PHOTO_PATH;
			File ff = new File(path);
			if (ff.isDirectory()) { // 如果路径是文件夹的时候
				l1 = g4.getFileSize(ff);
			} else {
				l1 = g4.getFileSizes(ff);
			}
			if(l1!=0){
				SettingCacheActivity.pic_inf.setText(g4.FormetFileSize(l1));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 初始化录音
	private static void init_records() {
		GetFileSize g5 = new GetFileSize();
		String path1 = VOICE_PATH;
		File ff1 = new File(path1);
		System.out.println("录音文件个数           " + g5.getlist(ff1));
		 System.out.println("目录");
		try {
			/*String path1 = VOICE_PATH;
			File ff1 = new File(path1);*/
			if (ff1.isDirectory()) { // 如果路径是文件夹的时候
				 System.out.println("录音文件个数           " + g5.getlist(ff1));
				 System.out.println("目录");
				l2 = g5.getFileSize(ff1);
				 System.out.println(path1 + "目录的大小为：" + l2+"转化为"+g5.FormetFileSize(l2));
				 if(l2!=0){
					 SettingCacheActivity.record_inf.setText(g5.FormetFileSize(l2));
				 }
				 
			} else {
				 System.out.println("     录音文件个数           1");
				 System.out.println("文件");
				l2 = g5.getFileSizes(ff1);
				 System.out.println(path1 + "文件的大小为：" +g5.FormetFileSize(l2));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 获取软件当前版本号
	private String getVersionName() throws Exception {
		// 获取packagemanager的实例
		PackageManager packageManager = getActivity().getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(getActivity()
				.getPackageName(), 0);
		String version = packInfo.versionName;
		return version;
	}

}
